import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_html/flutter_html.dart';

import '../common.dart';

class Detail extends StatefulWidget {
  Detail({super.key});
  @override
  State<Detail> createState() => _QGRulePageState();
}

class _QGRulePageState extends State<Detail> {
  // List<String> items = ['详情', '权益', '兑换'];
  List<String> items = ['详情', '权益'];
  int tindex = 0;
  final uuid = Get.parameters['uuid'];
  var info = {};
  var but = {};
  var thirdList = [];
  int isbox = 0;
  Map payInfo = {};

  List<Map<String, String>> textlist = [
    {
      "title": "关于退款",
      "text":
          "本藏品享受 7日内退款申请服务，前提为藏品未发生交易、转赠、寄售、兑换、提现或任何权益激活行为。 \n藏品一经使用（包括兑换提货券、发起转增、链上记录变更等），即视为放弃退款权利。 退款金额不包含平台可能产生的提现手续费、服务手续费等实际支出。",
    },
    {
      "title": "第三方数字提货券回收服务说明",
      "text":
          "为拓展用户数字提货券的灵活使用场景，平台开放技术接入端口，支持经平台审核的第三方独立服务机构提供提货券定向回收服务。 该第三方服务方拥有对每期或每日提货券回收数量的自主设定权与动态调整权，并对相关规则拥有最终解释权。 \n用户如暂不选择商品兑换，可自愿将所持数字提货券转交至服务方进行定向兑付。兑付比例一般不低于券面价值的60%-70%。 \n请用户在使用前充分了解服务方规则，自主决策并承担相应的操作后果与风险责任。",
    },
    {
      "title": "重要声明",
      "text":
          "数字提货券的第三方回收服务属于平台提供的用户便捷服务选项之一，不构成投资建议或价格承诺。平台仅提供技术接入及信息展示支持，相关服务的资金收付、履约责任及兑换流程均由第三方独立承担，与平台无直接法律或经济关系。用户应自行判断并了解服务条款及风险内容，自行决定是否使用，并自行承担由此产生的全部风险与责任。平台不构成担保、兑付义务或任何形式的收益承诺。 藏品兑换销毁机制 \n用户使用本平台的数字提货券兑换实物商品或平台权益后，该笔兑换对应的数字藏品将视为已完成链上权益履约，平台将对其进行链上标记与销毁处理。销毁后的藏品编号不再具有交易流通、转赠或再次兑换的功能。请用户在兑换前认真确认，以避免造成不必要的资产损失。",
    },
    {
      "title": "购买须知",
      "text":
          "本藏品面向 18周岁（不含）至60周岁（含） 的中国大陆实名认证用户开放购买。 \n请您在购买前充分了解本平台《用户协议》《交易须知》与《藏品规则》，谨慎决策，理性参与。 请勿进行任何场外交易、非官方推荐方式的资产转移或资金往来，防止遭遇诈骗。 \n本平台反对炒作行为，严禁任何以数字藏品为名义进行非法集资、传销、诈骗等违法活动。 所有藏品发售与流通均遵守《中华人民共和国数据安全法》《网络安全法》《消费者权益保护法》等法律法规。",
    },
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData(url: '/products/$uuid').then((res) {
      info = res['info'];
      but = res['but'];
      isbox = res['is_box'];
      getInfo();
      setState(() {});
    });
  }

  getInfo() {
    getData(url: '/wallet/walletStatus').then((res) {
      if (res['code'] == 11000) {
        PayWidget('需实名后才能开通钱包，现在去实名？', '1');
      } else {
        payInfo = res;
        // PayWidget('需实名后才能开通钱包，现在去实名？');
      }
    });

    //  getData('/wallet/walletStatus', {}, 'noload').then((res) {
    //     if (res['code'] == 11000) {
    //       PayWidget('需实名后才能开通钱包，现在去实名？', '1');
    //     } else {
    //       payInfo.value = res;
    //       // PayWidget('需实名后才能开通钱包，现在去实名？');
    //     }
    //     print(res['code']);
    //   });
  }

  @override
  Widget build(BuildContext context) {
    final totalw = MediaQuery.of(context).size.width / 2 - 20;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0XFFFFFFFF),
        centerTitle: true,
        leading: buildBackButton(context),
      ),
      backgroundColor: Color(0xFFFFFFFF),
      bottomNavigationBar: Container(
        padding: EdgeInsets.symmetric(horizontal: 25),
        margin: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
        height: 50,
        decoration: BoxDecoration(
          color: Color(0XFF0F172B),
          borderRadius: BorderRadius.circular(50),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text.rich(
              TextSpan(
                children: [
                  TextSpan(
                    text: '￥',
                    style: TextStyle(fontSize: 16.0, color: Color(0XFFFFFFFF)),
                  ),
                  TextSpan(
                    text: '${money(info['today_price'])}',
                    style: TextStyle(fontSize: 24.0, color: Color(0XFFFFFFFF)),
                  ),
                ],
              ),
            ),
            GestureDetector(
              onTap: () {
                if (but['buy']) {
                  postData(
                    url: '/products/orders',
                    data: {
                      'uuid': uuid,
                      'total': '1',
                      'url': "back.html?web=back",
                      'wallet': "HF",
                    },
                  ).then((res) {
                    if (res != null) {
                      if (kIsWeb) {
                        final uur = Uri.parse('${res['order']['pay_url']}');
                        launchUrl(uur, webOnlyWindowName: '_self');
                      } else {
                        Get.toNamed(
                          '/webview?url=${res['order']['pay_url']}&back=suu&id=${res['order']['id']}',
                        );
                      }
                    }
                  });
                }
                if (!but['is_login']) {
                  Get.offNamed('/');
                }
              },
              child: wText(
                text: '${but['but'] ?? ''}',
                color: 'FFFFFF',
                size: 18,
              ),
            ),
          ],
        ),
      ),
      body: ListView(
        padding: EdgeInsets.symmetric(horizontal: 15),
        children: [
          Stack(
            children: [
              wImage(url: '${info['thumb']}', borderRadius: 10),
              if (isbox == 1)
                Positioned(
                  bottom: 10,
                  right: 10,
                  child: GestureDetector(
                    onTap: () {
                      toNamed('/user/assets?index=1');
                    },
                    child: wImage(url: 'box', width: 30),
                  ),
                ),
            ],
          ),
          SizedBox(height: 15),
          RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: '${info['title']}',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
                WidgetSpan(
                  child: setInteger(1, w: 18),
                  alignment: PlaceholderAlignment.bottom,
                ),
              ],
              style: TextStyle(color: Color(0XFF0F172B)),
            ),
          ),
          SizedBox(height: 15),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              wText(text: '来自', color: '878b95', size: 14),
              SizedBox(width: 5),
              wImage(url: 'loggin', width: 22, height: 22, borderRadius: 22),
              SizedBox(width: 5),
              wText(text: '${info['copyright']}', color: '878b95', size: 14),
              wImage(url: 'xright', width: 12),
            ],
          ),
          SizedBox(height: 25),
          Container(
            decoration: BoxDecoration(
              border: Border(bottom: BorderSide(color: Color(0XFFF5F5F5))),
            ),
            child: Row(
              children: List.generate(items.length, (index) {
                return GestureDetector(
                  onTap: () {
                    tindex = index;
                    if (index == 2) {
                      getData(url: '/third/index').then((res) {
                        thirdList = res;
                        setState(() {});
                      });
                    } else {
                      setState(() {});
                    }
                  },
                  child: Container(
                    margin: EdgeInsets.only(right: 25),
                    padding: EdgeInsets.only(bottom: 10),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Color(
                            tindex == index ? 0XFF0F172B : 0xffF5F5F5,
                          ),
                        ),
                      ),
                    ),
                    child: wText(text: items[index], size: 14),
                  ),
                );
              }),
            ),
          ),

          if (tindex == 0)
            Container(
              margin: EdgeInsets.only(top: 15),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
              decoration: BoxDecoration(
                color: Color(0XFFF8F9FD),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Theme(
                data: Theme.of(context).copyWith(
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                ),
                child: ExpansionTile(
                  shape: Border(),
                  tilePadding: EdgeInsets.zero,
                  collapsedShape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.zero,
                  ),
                  title: wText(text: '基本详情', size: 18, bold: true),
                  initiallyExpanded: true,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(top: 10),
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0XFFFFFFFF),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                wText(text: '藏品名称', size: 10, color: '878b95'),
                                SizedBox(height: 3),
                                wText(
                                  text: '${info['title']}（具体名称视编号为准）',
                                  bold: true,
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10),
                      padding: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 10,
                      ),
                      decoration: BoxDecoration(
                        color: Color(0XFFFFFFFF),
                        borderRadius: BorderRadius.circular(5),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              wText(text: '版权所有', size: 10, color: '878b95'),
                              SizedBox(height: 3),
                              wText(text: '${info['copyright']}', bold: true),
                            ],
                          ),
                          wImage(url: 'hbottom', width: 12),
                        ],
                      ),
                    ),
                    SizedBox(height: 10),
                    Container(
                      margin: EdgeInsets.only(top: 10),
                      padding: EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 10,
                      ),
                      decoration: BoxDecoration(
                        color: Color(0XFFFFFFFF),
                        borderRadius: BorderRadius.circular(5),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              wText(text: '发行单位', size: 10, color: '878b95'),
                              SizedBox(height: 3),
                              wText(text: '${info['issue']}', bold: true),
                            ],
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 10),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0XFFFFFFFF),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,

                              children: [
                                wText(
                                  text: '首发价格(CNY）',
                                  size: 10,
                                  color: '878b95',
                                ),
                                SizedBox(height: 3),
                                wText(
                                  text: '${money(info['money_price'])}',
                                  bold: true,
                                ),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(width: 10),
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0XFFFFFFFF),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                wText(
                                  text: '当前价格(CNY）',
                                  size: 10,
                                  color: '878b95',
                                ),
                                SizedBox(height: 3),
                                wText(
                                  text: '${money(info['today_price'])}',
                                  bold: true,
                                  color: '6828FF',
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 10),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0XFFFFFFFF),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                wText(
                                  text: '藏品价值(CNY）',
                                  size: 10,
                                  color: '878b95',
                                ),
                                SizedBox(height: 3),
                                wText(
                                  text: '${money(info['max_price'])}',
                                  bold: true,
                                ),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(width: 10),
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0XFFFFFFFF),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                wText(
                                  text: '发行总量(份)',
                                  size: 10,
                                  color: '878b95',
                                ),
                                SizedBox(height: 3),
                                wText(
                                  text: '${info['release_num']}',
                                  bold: true,
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),

                    SizedBox(height: 10),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0XFFFFFFFF),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,

                              children: [
                                wText(text: '发售时间', size: 10, color: '878b95'),
                                SizedBox(height: 3),
                                wText(
                                  text: '${info['created_at']}',
                                  bold: true,
                                ),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(width: 10),
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0XFFFFFFFF),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                wText(text: '所属链网络', size: 10, color: '878b95'),
                                SizedBox(height: 3),
                                wText(text: '${info['link_name']}', bold: true),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),

                    SizedBox(height: 10),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0XFFFFFFFF),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,

                              children: [
                                wText(text: '合约地址', size: 10, color: '878b95'),
                                SizedBox(height: 3),
                                Row(
                                  children: [
                                    info.isNotEmpty &&
                                            info['link_address'].isNotEmpty
                                        ? wText(
                                          text:
                                              '${info['link_address'].substring(0, 3)}...${info['link_address'].substring(14, 18)}',
                                          bold: true,
                                        )
                                        : wText(text: '...'),

                                    SizedBox(width: 3),
                                    // GestureDetector(
                                    //   onTap: () {
                                    //     copy(context, info['link_address']);
                                    //   },
                                    //   child: wImage(url: 'copy', width: 12),
                                    // ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(width: 10),
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 10,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0XFFFFFFFF),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                wText(text: '支付方式', size: 10, color: '878b95'),
                                SizedBox(height: 3),
                                wText(text: '汇付天下 ST', bold: true),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

          if (tindex == 0 && info.isNotEmpty)
            Container(
              margin: EdgeInsets.only(top: 15),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
              decoration: BoxDecoration(
                color: Color(0XFFF8F9FD),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Theme(
                data: Theme.of(context).copyWith(
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                ),
                child: ExpansionTile(
                  shape: Border(),
                  tilePadding: EdgeInsets.zero,
                  collapsedShape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.zero,
                  ),
                  title: wText(text: '藏品介绍', size: 18, bold: true),
                  initiallyExpanded: true,
                  children: [Html(data: '${info['info']}')],
                ),
              ),
            ),
          if (tindex == 0 && info.isNotEmpty)
            Container(
              margin: EdgeInsets.only(top: 15),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
              decoration: BoxDecoration(
                color: Color(0XFFF8F9FD),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Theme(
                data: Theme.of(context).copyWith(
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                ),
                child: ExpansionTile(
                  shape: Border(),
                  tilePadding: EdgeInsets.zero,
                  collapsedShape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.zero,
                  ),
                  title: wText(text: '关于寄售', size: 18, bold: true),
                  initiallyExpanded: true,
                  children: [Html(data: '${info['about']}')],
                ),
              ),
            ),

          if (tindex == 0)
            for (var item in textlist)
              Container(
                margin: EdgeInsets.only(top: 15),
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                decoration: BoxDecoration(
                  color: Color(0XFFF8F9FD),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Theme(
                  data: Theme.of(context).copyWith(
                    splashColor: Colors.transparent,
                    highlightColor: Colors.transparent,
                  ),
                  child: ExpansionTile(
                    shape: Border(),
                    tilePadding: EdgeInsets.zero,
                    collapsedShape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.zero,
                    ),
                    title: wText(
                      text: '${item['title']}',
                      size: 18,
                      bold: true,
                    ),
                    initiallyExpanded: true,
                    children: [
                      wText(text: '${item['text']}', size: 14, height: 1.8),
                    ],
                  ),
                ),
              ),

          if (tindex == 1)
            Container(
              margin: EdgeInsets.only(top: 15),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
              decoration: BoxDecoration(
                color: Color(0XFFF8F9FD),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Theme(
                data: Theme.of(context).copyWith(
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                ),
                child: ExpansionTile(
                  shape: Border(),
                  tilePadding: EdgeInsets.zero,
                  collapsedShape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.zero,
                  ),
                  title: wText(text: '藏品权益', size: 18, bold: true),
                  initiallyExpanded: true,
                  children: [Html(data: '${info['interests']}')],
                ),
              ),
            ),

          if (tindex == 2)
            GestureDetector(
              onTap: () async {
                var params = {'token': myget('token') ?? ''};
                final uri = Uri.parse(baseUrl).replace(queryParameters: params);
                if (await canLaunchUrl(uri)) {
                  await launchUrl(uri);
                } else {
                  throw '无法打开链接: $uri';
                }
              },
              child: wImage(url: 'quye'),
            ),
          if (tindex == 2)
            Wrap(
              spacing: 10,
              runSpacing: 10,
              children: [
                for (var item in thirdList.asMap().entries)
                  GestureDetector(
                    onTap: () async {
                      var params = {'token': myget('token') ?? ''};
                      final uri = Uri.parse(
                        baseUrl,
                      ).replace(queryParameters: params);
                      if (await canLaunchUrl(uri)) {
                        await launchUrl(uri);
                      } else {
                        throw '无法打开链接: $uri';
                      }
                    },
                    child: Container(
                      margin: EdgeInsets.only(top: 10),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Stack(
                            children: [
                              wImage(
                                url: '${item.value['thumb']}',
                                width: totalw,
                                height: totalw,
                                borderRadius: 10,
                              ),
                              // Positioned(
                              //   top: 10,
                              //   left: 10,
                              //   child: wImage(url: 'xiyou', width: 56),
                              // ),
                            ],
                          ),
                          SizedBox(height: 3),
                          wText(
                            text: '${item.value['title']}',
                            size: 14,
                            bold: true,
                          ),
                          SizedBox(height: 2),
                          wText(
                            text: '可兑换${item.value['stock']}份',
                            color: '878b95',
                          ),
                        ],
                      ),
                    ),
                  ),
              ],
            ),
        ],
      ),
    );
  }
}
